package io.gimo.study.design_pattern.factory.abstract_factory.product;


import io.gimo.study.design_pattern.factory.abstract_factory.Searcher;

public class BinarySearcher implements Searcher {

	@Override
	public int search(int[] target, int search_key) {
		int low = 0;   
        int high = target.length-1;   
        while(low <= high) {   
            int middle = (low + high)/2;   
            if(search_key == target[middle]) {   
                return middle;   
            }else if(search_key <target[middle]) {   
                high = middle - 1;   
            }else {   
                low = middle + 1;   
            }  
        }  
        return -1;
	}

	public int search(int[] target,int search_key,int beginIndex,int endIndex){
		int midIndex = (beginIndex+endIndex)/2;    
	       if(search_key <target[beginIndex]||search_key>target[endIndex]||beginIndex>endIndex){  
	           return -1;    
	       }  
	       if(search_key <target[midIndex]){    
	           return search(target,search_key,beginIndex,midIndex-1);    
	       }else if(search_key>target[midIndex]){    
	           return search(target,search_key,midIndex+1,endIndex);    
	       }else {    
	           return midIndex;    
	       }    
	}
}
